package com.zlmediakit.service;

import android.app.Activity;
import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

import com.zlmediakit.jni.ZLMediaKit;

/**
 * @AUTHOR fengyook
 * @DATE 2021/10/28 17:03
 * @DES
 */
public class MediaService extends Service {

    String TAG = "MediaService";

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.INTERNET"};

    Context context;
    private ZLMediaKit.MediaPlayer _player;
    private ZLMediaKit.MediaPlayerCallBack mediaPlayerCallBack;
    private ZLMediaKit.MediaFrame _mediaFrame;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            this.startForeground();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    public void startForeground() {
        NotificationBuilder builder = new NotificationBuilder(this);
        final Notification notification = builder.buildNotification();
        startForeground(NotificationBuilder.NOTIFICATION_ID, notification);
        startMediaServer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 设备开启mediaserver服务
     */
    public void startMediaServer() {
        boolean permissionSuccess = true;
        for (String str : PERMISSIONS_STORAGE) {
            int permission = ActivityCompat.checkSelfPermission(this, str);
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions((Activity) this.getApplicationContext(), PERMISSIONS_STORAGE, 1);
                permissionSuccess = false;
                break;
            }
        }
        String sdDir = Environment.getExternalStorageState();
        if (permissionSuccess) {
            Toast.makeText(this, "你可以修改配置文件再启动：" + sdDir + "/zlmediakit.ini", Toast.LENGTH_LONG).show();
            Toast.makeText(this, "SSL证书请放置在：" + sdDir + "/zlmediakit.pem", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "请给予我权限，否则无法启动测试！", Toast.LENGTH_LONG).show();
        }
        ZLMediaKit.startDemo(sdDir);
    }

}
